package etxt2db.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Class holding functions able to extract the contents zip archive files.
 * <p>
 * 
 * @author Gonçalo Simões
 * @author Rui Lageira
 *
 */
public class ArchiveUnZipper {
	
	static final int BUFFER = 2048;
	
	/**
	 * Extracts the contents of a generic zip file to a target directory.
	 * <p>
	 * @param file				the file to unzip
	 * @param destinationPath	the target directory
	 * @throws IOException		if an input/output error occurs
	 */
	public static void unzip(File file, String destinationPath) throws IOException {
		BufferedOutputStream dest = null;
		BufferedInputStream is = null;
		ZipEntry entry;
		ZipFile zipfile = new ZipFile(file);
		Enumeration<? extends ZipEntry> e = zipfile.entries();
		if (e.hasMoreElements()) {
			(new File(destinationPath)).mkdirs();
		}
		while (e.hasMoreElements()) {
			entry = (ZipEntry) e.nextElement();
			System.out.println("Extracting: " + entry);
			is = new BufferedInputStream(zipfile.getInputStream(entry));
			int count;
			byte data[] = new byte[BUFFER];
			String dir = getDir(entry.getName());
			if (dir != null) {
				(new File(destinationPath + "/" + dir)).mkdirs();
			}
			File f = new File(destinationPath + "/" + entry.getName());
			System.out.println("creating new file " + destinationPath + "/"
					+ entry.getName());
			f.createNewFile();
			FileOutputStream fos = new FileOutputStream(destinationPath + "/" + entry.getName());
			dest = new BufferedOutputStream(fos, BUFFER);
			while ((count = is.read(data, 0, BUFFER)) != -1) {
				dest.write(data, 0, count);
			}
			dest.flush();
			dest.close();
			is.close();
		}
	}
	
	/**
	 * Computes the directory of a file, provided his path.
	 * <p>
	 * @param filePath	the path to the file
	 * @return	the directory of the file
	 */
	private static String getDir(String filePath) {
		
		String[] tokens = filePath.split("/");
		String dir = new String();
		int i;
		for(i = 0; i < tokens.length-1; i++) {
			if(dir==null) {
				dir = "";
			}
			dir += tokens[i];
			if(i<tokens.length-2) {
				dir += "/";
			}
		}
		return dir;
	}
	
}